import React, { useState, useEffect } from 'react';
import {
    TextField, Button, Select, MenuItem, FormControl, InputLabel,
    IconButton, Grid, Typography, Box, Paper, Stack
} from '@mui/material';
import { Add as AddIcon, Delete as DeleteIcon } from '@mui/icons-material';

const ConfigurationForm = ({ config, onInputChange, onSubmit, onReset }) => {
    const [fields, setFields] = useState([]);

    useEffect(() => {
        if (config.fields) {
            setFields(config.fields);
        } else {
            setFields([{
                fieldName: '',
                fieldType: '',
                minValue: '',
                maxValue: '',
                prefix: '',
                suffix: '',
                format: '',
                fieldOrder: 0
            }]);
        }
    }, [config]);

    const handleAddField = () => {
        setFields([...fields, {
            fieldName: '',
            fieldType: '',
            minValue: '',
            maxValue: '',
            prefix: '',
            suffix: '',
            format: '',
            fieldOrder: fields.length
        }]);
    };

    const handleRemoveField = (index) => {
        setFields(fields.filter((_, i) => i !== index));
    };

    const handleFieldChange = (index, field, value) => {
        const newFields = [...fields];
        newFields[index] = { ...newFields[index], [field]: value };
        setFields(newFields);
    };

    const handleFormSubmit = (e) => {
        e.preventDefault();
        const formData = {
            ...config,
            fields: fields.map((field, index) => ({
                ...field,
                fieldOrder: index
            }))
        };
        onSubmit(formData);
    };

    return (
        <form onSubmit={handleFormSubmit}>
            <Grid container spacing={3}>
                <Grid item xs={12}>
                    <Box sx={{ 
                        p: 2, 
                        bgcolor: 'background.default',
                        borderRadius: 1
                    }}>
                        <Grid container spacing={2}>
                            <Grid item xs={12} md={4}>
                                <TextField
                                    name="configName"
                                    label="配置名称"
                                    value={config.configName}
                                    onChange={onInputChange}
                                    fullWidth
                                    required
                                    sx={{ bgcolor: 'white' }}
                                />
                            </Grid>
                            <Grid item xs={12} md={4}>
                                <TextField
                                    name="description"
                                    label="配置描述"
                                    value={config.description}
                                    onChange={onInputChange}
                                    fullWidth
                                    sx={{ bgcolor: 'white' }}
                                />
                            </Grid>
                            <Grid item xs={12} md={4}>
                                <TextField
                                    name="dataCount"
                                    label="生成数量"
                                    type="number"
                                    value={config.dataCount}
                                    onChange={onInputChange}
                                    fullWidth
                                    required
                                    sx={{ bgcolor: 'white' }}
                                />
                            </Grid>
                        </Grid>
                    </Box>
                </Grid>

                {fields.map((field, index) => (
                    <Grid item xs={12} key={index}>
                        <Paper 
                            elevation={2}
                            sx={{
                                p: 2,
                                position: 'relative',
                                '&:hover': {
                                    boxShadow: 3
                                }
                            }}
                        >
                            <Grid container spacing={2} alignItems="center">
                                <Grid item xs={11}>
                                    <Typography 
                                        variant="h6" 
                                        color="primary"
                                        sx={{ mb: 2 }}
                                    >
                                        字段 {index + 1}
                                    </Typography>
                                </Grid>
                                <Grid item xs={1}>
                                    <IconButton 
                                        onClick={() => handleRemoveField(index)} 
                                        color="error"
                                        sx={{
                                            position: 'absolute',
                                            top: 8,
                                            right: 8
                                        }}
                                    >
                                        <DeleteIcon />
                                    </IconButton>
                                </Grid>
                                <Grid item xs={6}>
                                    <TextField
                                        label="字段名称"
                                        value={field.fieldName}
                                        onChange={(e) => handleFieldChange(index, 'fieldName', e.target.value)}
                                        fullWidth
                                    />
                                </Grid>
                                <Grid item xs={6}>
                                    <FormControl fullWidth>
                                        <InputLabel>字段类型</InputLabel>
                                        <Select
                                            value={field.fieldType}
                                            onChange={(e) => handleFieldChange(index, 'fieldType', e.target.value)}
                                        >
                                            <MenuItem value="uuid">UUID</MenuItem>
                                            <MenuItem value="name">姓名</MenuItem>
                                            <MenuItem value="age">年龄</MenuItem>
                                            <MenuItem value="phone">电话</MenuItem>
                                            <MenuItem value="email">邮箱</MenuItem>
                                            <MenuItem value="date">日期</MenuItem>
                                            <MenuItem value="city">城市</MenuItem>
                                            <MenuItem value="number">数字</MenuItem>
                                            <MenuItem value="text">文本</MenuItem>
                                        </Select>
                                    </FormControl>
                                </Grid>
                                
                                {(field.fieldType === 'age' || field.fieldType === 'number') && (
                                    <>
                                        <Grid item xs={6}>
                                            <TextField
                                                label="最小值"
                                                type="number"
                                                value={field.minValue}
                                                onChange={(e) => handleFieldChange(index, 'minValue', e.target.value)}
                                                fullWidth
                                            />
                                        </Grid>
                                        <Grid item xs={6}>
                                            <TextField
                                                label="最大值"
                                                type="number"
                                                value={field.maxValue}
                                                onChange={(e) => handleFieldChange(index, 'maxValue', e.target.value)}
                                                fullWidth
                                            />
                                        </Grid>
                                    </>
                                )}
                                
                                {field.fieldType === 'date' && (
                                    <Grid item xs={12}>
                                        <TextField
                                            label="日期格式"
                                            value={field.format || 'yyyy-MM-dd'}
                                            onChange={(e) => handleFieldChange(index, 'format', e.target.value)}
                                            helperText="例如：yyyy-MM-dd, yyyy/MM/dd HH:mm:ss"
                                            fullWidth
                                        />
                                    </Grid>
                                )}
                                
                                {(field.fieldType === 'name' || field.fieldType === 'text') && (
                                    <>
                                        <Grid item xs={4}>
                                            <TextField
                                                label="前缀"
                                                value={field.prefix}
                                                onChange={(e) => handleFieldChange(index, 'prefix', e.target.value)}
                                                fullWidth
                                            />
                                        </Grid>
                                        <Grid item xs={4}>
                                            <TextField
                                                label="后缀"
                                                value={field.suffix}
                                                onChange={(e) => handleFieldChange(index, 'suffix', e.target.value)}
                                                fullWidth
                                            />
                                        </Grid>
                                        <Grid item xs={4}>
                                            <FormControl fullWidth>
                                                <InputLabel>格式</InputLabel>
                                                <Select
                                                    value={field.format || ''}
                                                    onChange={(e) => handleFieldChange(index, 'format', e.target.value)}
                                                >
                                                    <MenuItem value="">默认</MenuItem>
                                                    <MenuItem value="lastName_firstName">姓在前</MenuItem>
                                                </Select>
                                            </FormControl>
                                        </Grid>
                                    </>
                                )}
                                
                                {field.fieldType === 'number' && (
                                    <Grid item xs={12}>
                                        <TextField
                                            label="格式化模板"
                                            value={field.format}
                                            onChange={(e) => handleFieldChange(index, 'format', e.target.value)}
                                            helperText="例如：%04d 表示4位数字，不足补0"
                                            fullWidth
                                        />
                                    </Grid>
                                )}
                            </Grid>
                        </Paper>
                    </Grid>
                ))}

                <Grid item xs={12}>
                    <Button
                        type="button"
                        variant="outlined"
                        startIcon={<AddIcon />}
                        onClick={handleAddField}
                        fullWidth
                        sx={{ 
                            py: 1,
                            bgcolor: 'background.paper',
                            '&:hover': {
                                bgcolor: 'background.default'
                            }
                        }}
                    >
                        添加字段
                    </Button>
                </Grid>

                <Grid item xs={12}>
                    <Stack direction="row" spacing={2} justifyContent="flex-end">
                        <Button 
                            type="submit" 
                            variant="contained" 
                            color="primary"
                            size="large"
                        >
                            {config.id ? '更新配置' : '保存配置'}
                        </Button>
                        <Button 
                            type="button" 
                            variant="outlined" 
                            color="secondary"
                            size="large"
                            onClick={onReset}
                        >
                            重置
                        </Button>
                    </Stack>
                </Grid>
            </Grid>
        </form>
    );
};

export default ConfigurationForm; 